package com.xy.webadmin.app.config;

import com.xy.webadmin.app.model.MqttBrokerConfig;
import com.xy.webadmin.app.service.MqttBrokerConfigService;
import com.xy.webadmin.app.service.MqttClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * MQTT客户端初始化器，负责在应用启动时加载所有MQTT配置并建立连接
 * 使用Spring Integration MQTT
 *
 * @author xiaoyue
 * @date 2025-07-03
 */
@Slf4j
@Component
public class MqttClientInitializer implements CommandLineRunner {

    @Autowired
    private MqttBrokerConfigService mqttBrokerConfigService;
    
    @Autowired
    private MqttClientManager mqttClientManager;
    
    @Autowired
    private MqttSubscribeAdapterConfig mqttSubscribeAdapterConfig;
    
    @Override
    public void run(String... args) {
        log.info("开始从数据库初始化MQTT客户端...");
        
        try {
            // 获取所有活跃的MQTT配置
            List<MqttBrokerConfig> configs = mqttBrokerConfigService.getMqttBrokerConfigList(null, null);
            
            log.info("找到{}个MQTT配置", configs.size());
            
            // 记录每个配置的基本信息
            if (configs.size() > 0) {
                log.info("MQTT配置详情:");
                for (MqttBrokerConfig config : configs) {
                    log.info("配置ID: {}, 名称: {}, 公司ID: {}, 代理URL: {}, 客户端ID: {}", 
                            config.getId(), config.getName(), config.getCompanyId(), 
                            config.getBrokerUrl(), config.getClientId());
                }
            }
            
            // 注册每个MQTT客户端
            int successCount = 0;
            for (MqttBrokerConfig config : configs) {
                try {
                    log.info("开始注册MQTT客户端, 配置ID: {}, 名称: {}", config.getId(), config.getName());
                    mqttClientManager.registerMqttClient(config);
                    log.info("成功注册MQTT客户端, 配置ID: {}, 名称: {}, 公司ID: {}", 
                            config.getId(), config.getName(), config.getCompanyId());
                    successCount++;
                } catch (Exception e) {
                    log.error("注册MQTT客户端失败, 配置ID: {}, 名称: {}, 错误: {}", 
                            config.getId(), config.getName(), e.getMessage(), e);
                }
            }
            
            log.info("MQTT客户端注册完成, 成功: {}/总计: {}", successCount, configs.size());
            
            // 初始化订阅
            log.info("开始注册MQTT默认订阅...");
            mqttSubscribeAdapterConfig.registerDefaultSubscriptions();
            log.info("MQTT客户端初始化完成");
        } catch (Exception e) {
            log.error("初始化MQTT客户端时发生错误: {}", e.getMessage(), e);
        }
    }
} 